package com.bai.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.bai.edu.entity.Subject;
import com.bai.edu.entity.excel.SubjectData;
import com.bai.edu.entity.subject.OneSubject;
import com.bai.edu.entity.subject.TwoSubject;
import com.bai.edu.listener.SubjectExcelListener;
import com.bai.edu.mapper.SubjectMapper;
import com.bai.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author bai
 * @since 2023-07-23
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    //TODO:添加课程分类
    @Override
    public void saveSubject(MultipartFile file,SubjectService subjectService) {
        try {
            //得到文件输入流
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //TODO:课程分类列表
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询出所有的一级分类
        LambdaQueryWrapper<Subject> wrapperOne = new LambdaQueryWrapper<>();
        wrapperOne.eq(Subject::getParentId,"0" );
        List<Subject> Onesubjects = baseMapper.selectList(wrapperOne);
        //查询出所有的二级分类
        LambdaQueryWrapper<Subject> wrapperTwo = new LambdaQueryWrapper<>();
        wrapperTwo.ne(Subject::getParentId,"0" );
        List<Subject> Twosubjects = baseMapper.selectList(wrapperOne);

        //封装数据
        List<OneSubject> list = new ArrayList<>();
        for (Subject onesubject : Onesubjects) {
            OneSubject oneSubject = new OneSubject();
            /* oneSubject.setId(onesubject.getId());
               oneSubject.setTitle(onesubject.getTitle());  */
            BeanUtils.copyProperties(onesubject,oneSubject);
            list.add(oneSubject);

            List<TwoSubject> twoSubjects = new ArrayList<>();
            for (Subject twoSubject : Twosubjects) {
                TwoSubject subject = new TwoSubject();
                if (twoSubject.getParentId().equals(oneSubject.getId())){
                    BeanUtils.copyProperties(twoSubject,subject);
                    twoSubjects.add(subject);
                }
            }
            oneSubject.setChildren(twoSubjects);
        }


        return list;
    }
}
